<template>
  <el-dialog 
    :close-on-click-modal="false"
    :visible="true"
    :show-close="false"
    width="80%">

    <div class="print-content" ref="pdfContent">
    <div slot="title" class="title">训练2</div>
    <el-form ref="form" :model="form" label-position="right">
      <el-row class="header">
        <el-col :span="6">
          <span>姓名：</span>
          <span>{{ pilot ? pilot.name : '' }}</span>
        </el-col>
        <el-col :span="6">
          <span>性别：</span>
          <span>{{ pilot ? (pilot.gender === 1 ? '男' : '女') : '' }}</span>
        </el-col>
        <el-col :span="6">
          <span>出生年月：</span>
          <span>{{ pilot ? pilot.birthdate : '' }}</span>
        </el-col>
        <el-col :span="6">
          <span>部职别：</span>
          <span>{{ pilot ? pilot.position : '' }}</span>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-table :data="tableData">
            <el-table-column prop="parameter" label="生理参数" />
            <el-table-column prop="xlq" label="训练前" />
            <el-table-column label="4.0-6.0kPa">
              <el-table-column
                prop="xl461"
                label="1min"
                width="120" />
              <el-table-column
                prop="xl462"
                label="2min"
                width="120" />
              <el-table-column
                prop="xl463"
                label="3min"
                width="120" />
            </el-table-column>
            <el-table-column prop="xl46Xyh" label="卸压后3-5分钟" />
            <el-table-column prop="xl68" label="6.0-8.0kPa" />
            <el-table-column prop="xl68Xyh" label="卸压后3-5分钟" />
            <el-table-column prop="xl810" label="8.0-10.0kPa" />
            <el-table-column prop="xl810Xyh" label="卸压后" />
          </el-table>
        </el-col>
      </el-row>

    <el-row style="margin-bottom: 20px;">
        <el-form-item label="主观感受">
          <div v-html="feelNames"></div>
        </el-form-item>
    </el-row>

    <el-row>
        <el-form-item label="结果评定">
          <span>{{form.rate}}</span>
        </el-form-item>

    </el-row>

    <el-row>
        <el-form-item label="结果建议">
          <span>{{ printData.jy }}</span>
        </el-form-item>
    </el-row>

    <el-row>
      <el-col :span="4">
        <el-form-item label="记录人">
          <span>{{ printData.createBy }}</span>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="日期">
          <span>{{printData.createTime}}</span>
        </el-form-item>
      </el-col>
    </el-row>

  </el-form>
    </div>
  <div slot="footer" class="dialog-footer">
    <el-button type="text" @click="handleExport">导出PDF</el-button>
    <el-button type="text" @click="$emit('close', '')">取消</el-button>
  </div>
</el-dialog>
</template>

<script>
import { RATE_RESULTS} from '@/utils/constants'
import jsPDF from 'jspdf'
import html2canvas from 'html2canvas'
import { convertFeelsToString } from '@/utils/feel'

export default {
  name: 'PrintDialog',
  props: {
    printData: Object,
    pilot: {
      type: Object,
      default: null
    }
  },
  computed: {
    // 将感受ID转换为名称
    feelNames() {
      return convertFeelsToString(this.printData.feels)
    }
  },
  data() {
    return {
      // title: '地面加压呼吸训练记录单',
      tableData: [
        { parameter: '心率（次/分）'},
        { parameter: '呼吸（次/分）'},
        { parameter: '血压（mmHg）'}
      ],
      form: {
        name: 'test',
        feels: '',
        rate: '',
        gender: '男',
        otherFeel: ''
      },
      rates: RATE_RESULTS,
    };
  },
  mounted() {
    this.initForm();
    this.initTableData();
    console.log(this.pilot);
  },
  methods: {
    initForm() {
      this.form.rate = this.rates.get(this.printData.result)
      console.log(this.form, this.printData);
    },
    initTableData() {
      const xlq = this.printData.xlq.split('|');
      const xl461 = this.printData.xl461.split('|');
      const xl462 = this.printData.xl462.split('|');
      const xl463 = this.printData.xl463.split('|');

      const xl46Xyh = this.printData.xl46Xyh.split('|');
      const xl68 = this.printData.xl68.split('|');
      const xl68Xyh = this.printData.xl68Xyh.split('|');
      const xl810 = this.printData.xl810.split('|');
      const xl810Xyh = this.printData.xl810Xyh.split('|');
      for (let i = 0; i < this.tableData.length; i++) {
        this.tableData[i].xlq = xlq[i];
        this.tableData[i].xl461 = xl461[i];
        this.tableData[i].xl462 = xl462[i];
        this.tableData[i].xl463 = xl463[i];
        this.tableData[i].xl46Xyh = xl46Xyh[i];
        this.tableData[i].xl68 = xl68[i];
        this.tableData[i].xl68Xyh = xl68Xyh[i];
        this.tableData[i].xl810 = xl810[i];
        this.tableData[i].xl810Xyh = xl810Xyh[i];
      }
      console.log(this.tableData)
    },
    async handleExport() {
      try {
        const content = this.$refs.pdfContent;
        if (!content) {
          this.$message.error('未找到导出内容');
          return;
        }
        const canvas = await html2canvas(content, { scale: 2 });
        const imgData = canvas.toDataURL('image/jpeg', 1.0);
        const pdf = new jsPDF('p', 'mm', 'a4');
        // 计算图片宽高自适应A4
        const pageWidth = pdf.internal.pageSize.getWidth();
        const pageHeight = pdf.internal.pageSize.getHeight();
        const imgWidth = pageWidth;
        const imgHeight = canvas.height * (imgWidth / canvas.width);
        let position = 0;
        if (imgHeight < pageHeight) {
          pdf.addImage(imgData, 'JPEG', 0, position, imgWidth, imgHeight);
        } else {
          // 多页处理
          let leftHeight = imgHeight;
          let pageData = imgData;
          while (leftHeight > 0) {
            pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight);
            leftHeight -= pageHeight;
            if (leftHeight > 0) {
              pdf.addPage();
              position = 0;
            }
          }
        }
        const pilotName = this.pilot ? this.pilot.name : '未知';
        pdf.save(`训练2-${pilotName}-导出.pdf`);
      } catch (e) {
        this.$message.error('导出失败: ' + e.message);
      }
    }
  }
}
</script>

<style scoped>

.title {
  text-align: center;
  font-size: 30px;
  font-weight: bold;
  margin-bottom: 20px;
}
.print-content {
  padding: 0 20px;
}
.el-form-item {
  display: flex;
  margin-bottom: 10px;
}
.el-row {
  margin-bottom: 10px;
}
</style>
